package com.yidu.hbatsams.service.Impl;

import com.github.pagehelper.PageHelper;
import com.yidu.hbatsams.dao.*;
import com.yidu.hbatsams.domain.*;
import com.yidu.hbatsams.domain.vo.UserVo;
import com.yidu.hbatsams.service.AtsSchemeServicefx;
import com.yidu.hbatsams.utils.ExportWordTools.ExportWordAddData;
import com.yidu.hbatsams.utils.ExportWordTools.XWPFHelper;
import com.yidu.hbatsams.utils.FileTools;
import com.yidu.hbatsams.utils.Tools;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class AtsSchemeImplfx implements AtsSchemeServicefx {
    @Resource
    private AtsSchemeMapperfx atsSchemeMapperfx;
    @Resource
    private AtsEmpCoachMapper atsEmpCoachMapper;
    @Resource
    private FileTools fileTools;
    @Resource
    private AtsEmpAthleteMapper atsEmpAthleteMapper;
    @Resource
    private AtsSchemeAthleteMapperfx atsSchemeAthleteMapperfx;
    @Resource
    private AtsSchemeExpertMapperfx atsSchemeExpertMapperfx;
    @Resource
    private AtsSchemeAuditMapperfx atsSchemeAuditMapperfx;

    /**
     * 查询所有
     * @param pageSize
     * @param pageNum
     * @param schemeType
     * @return
     */
    @Override
    public List<AtsScheme> findAll(Integer pageSize, Integer pageNum,String schemeType,String schemeName,String stime,String etime,Integer coachId,Integer schemeId,String athleteId,Integer expertId,Integer num,HttpSession session) {
       UserVo userVo = (UserVo)session.getAttribute("user");
        if(userVo.getCompanyId().equals("4")){
            PageHelper.offsetPage(pageNum,pageSize);
            PageHelper.startPage(pageNum,pageSize);
            List<AtsScheme> athlete = atsSchemeMapperfx.findAthlete(schemeType,schemeName,stime,etime,userVo.getClerkId());
            for(int i=0;i<athlete.size();i++){
                List<AtsSchemeAthlete> athletes = atsSchemeAthleteMapperfx.findAthleteQuanxian(schemeType,userVo.getClerkId());
                if(athletes.size()>0){
                    athlete.get(i).setAthleteName(athletes.get(0).getAthleteName());

                }
            }
            return athlete;
        }
       else if(userVo.getCompanyId().equals("2")){
            PageHelper.offsetPage(pageNum,pageSize);
            PageHelper.startPage(pageNum,pageSize);
            List<AtsScheme> coach = atsSchemeMapperfx.findCoach(schemeType,schemeName,stime,etime,Integer.valueOf(userVo.getClerkId()));
            return coach;
        }else if(userVo.getCompanyId().equals("3")){
            PageHelper.startPage(pageNum,pageSize);
            List<AtsScheme> expert = atsSchemeMapperfx.findExpert(schemeType,schemeName,stime,etime,Integer.valueOf(userVo.getClerkId()));
            for(int i=0;i<expert.size();i++){
                List<AtsSchemeExpert> expertList = atsSchemeExpertMapperfx.findExpert(schemeType,expert.get(i).getSchemeId());
                if(expertList.size()>0){
                    expert.get(i).setAuditState(expertList.get(0).getAuditState());
                    expert.get(i).setApplyForTime(expertList.get(0).getApplyForTime());
                    expert.get(i).setApplyForExp(expertList.get(0).getApplyForExp());
                    expert.get(i).setResults(expertList.get(0).getResults());
                }
            }
            return expert;
        }else{
            PageHelper.offsetPage(pageNum,pageSize);
            PageHelper.startPage(pageNum,pageSize);
            List<AtsScheme> list = atsSchemeMapperfx.findAll(schemeType,schemeName,stime,etime);
           for(int i=0;i<list.size();i++){
                List<AtsSchemeExpert> expertList = atsSchemeExpertMapperfx.findExpert(schemeType,list.get(i).getSchemeId());
                if(expertList.size()>0){
                    list.get(i).setAuditState(expertList.get(0).getAuditState());
                    list.get(i).setApplyForTime(expertList.get(0).getApplyForTime());
                    list.get(i).setApplyForExp(expertList.get(0).getApplyForExp());
                    list.get(i).setResults(expertList.get(0).getResults());
                }
               List<AtsSchemeAthlete> athletes = atsSchemeAthleteMapperfx.findAthleteQuanxianLeaAdmin(schemeType,list.get(i).getSchemeId());
               if(athletes.size()>0){
                   list.get(i).setAthleteName(athletes.get(0).getAthleteName());
                   System.out.println(athletes.get(0).getAthleteName()+"...............");
               }
           }
           return list;
        }

    }

    @Override
    public List<AtsSchemeAudit> findAduits(Integer saId) {
        List<AtsSchemeAudit> list = atsSchemeAuditMapperfx.findAduits(saId);
        return list;
    }

    /**
     * 查询下拉框教练表
     * @param coachName
     * @return
     */
    public List<AtsEmpCoach> findAllselect(String coachName) {
        //List<AtsEmpCoach> list = atsEmpCoachMapper.selectAll(coachName);

        //return list;
        return  null;
    }
    /**
     * 查询方案对应运动员表
     * @param schemeId
     * @return
     */
    @Override
    public List<AtsSchemeAthlete> selectCheckbox(Integer schemeId) {

        List<AtsSchemeAthlete> list = atsSchemeAthleteMapperfx.selectCheckbox(schemeId);

        return list;
    }


    @Override
    public AtsScheme findById(Integer schemeId) {
        AtsScheme atsScheme = atsSchemeMapperfx.findById(schemeId);
       // String str = atsScheme.getYear()+"-"+atsScheme.getMonth();
        //atsScheme.setMonth(str);
        return atsScheme;
    }

    /**
     * 分页
     * @param schemeType
     * @return
     */
    @Override
    public int count(String schemeType,String schemeName,String stime,String etime,HttpSession session) {
        UserVo userVo = (UserVo)session.getAttribute("user");
        if(userVo.getCompanyId().equals("4")){
            return atsSchemeMapperfx.countAthlete(schemeType,schemeName,stime,etime,userVo.getClerkId());
        }else if(userVo.getCompanyId().equals("2")){
            return atsSchemeMapperfx.countCoach(schemeType,schemeName,stime,etime,Integer.valueOf(userVo.getClerkId()));
        }else if(userVo.getCompanyId().equals("3")){
            return atsSchemeMapperfx.countExpert(schemeType,schemeName,stime,etime,Integer.valueOf(userVo.getClerkId()));
        }else{
            return atsSchemeMapperfx.count(schemeName,stime,etime,schemeType);
        }


    }

    @Override
    public int deleteByPrimaryKey(Integer schemeId) {
        return 0;
    }

    @Override
    public int insert(AtsScheme record) {
        return 0;
    }

    /**
     * 增加
     * @param record
     * @param file
     * @param file2
     * @param file3
     * @return
     */
    @Override
    public int insertSelective(AtsScheme record, MultipartFile file,MultipartFile file2,MultipartFile file3,HttpSession session) {
        int num = 0 ;
        for (int i = 0 ; i < 1 ; i--){
            num = Tools.getRandomNumber(2147483647);
            AtsScheme atsScheme  = atsSchemeMapperfx.selectByPrimaryKey(num);
            if(atsScheme==null){
                break ;
            }
        }
        record.setSchemeId(num);
        record.setSchemeType("心理训练方案");
       record.setIsva(1);

        record.setCreatTime(new java.sql.Date(System.currentTimeMillis()));
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        UserVo userVo = (UserVo)session.getAttribute("user");
        record.setCoachId(Integer.valueOf(userVo.getClerkId()));
        record.setCoachName(userVo.getUserName());
        record.setYear(calendar.get(Calendar.YEAR));
        record.setMonth(calendar.get(Calendar.MONTH) + 1);
        AtsEmpCoach atsEmpCoach = atsEmpCoachMapper.selectByPrimaryKey(record.getCoachId());
       record.setCoachName(atsEmpCoach.getCoachName());
       if(record.getAthleteId()!=null &&!record.getAthleteId().equals("")){
           String[] str = record.getAthleteId().split(",");

           for(int i=0;i<str.length;i++){

               AtsSchemeAthlete atsSchemeAthlete = new AtsSchemeAthlete();
               atsSchemeAthlete.setSchemeId(num);
               atsSchemeAthlete.setSchemeName(record.getSchemeName());
               atsSchemeAthlete.setAthleteId(Integer.valueOf(str[i]));

               AtsEmpAthlete athlete = atsEmpAthleteMapper.selectByPrimaryKey(Integer.valueOf(str[i]));

               atsSchemeAthlete.setAthleteName(athlete.getAthleteName());
               atsSchemeAthlete.setIsRead(" ");
               atsSchemeAthleteMapperfx.insertSelective(atsSchemeAthlete);
           }
       }
        try {



            if(file.isEmpty()){
                record.setFile1(null);
            }else{
                String fileOne = fileTools.saveFile("atsScheme",file);

                record.setFile1(fileOne);
            }

            if(file2.isEmpty()){
                record.setFile2(null);
            }else{
                String fileTwo = fileTools.saveFile("atsScheme",file2);

                record.setFile2(fileTwo);
            }

            if(file3.isEmpty()){
                record.setFile3(null);
            }else{
                String fileThree = fileTools.saveFile("atsScheme",file3);

                record.setFile3(fileThree);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        int row = atsSchemeMapperfx.insertSelective(record);
        return row;
    }

    /**
     * 反馈意见
     * @param record
     * @param resultFile
     * @return
     */
    @Override
    public int insertResult(AtsScheme record, MultipartFile resultFile,Integer schemeId) throws IOException {
        AtsScheme atsScheme = atsSchemeMapperfx.findById(schemeId);
        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        atsScheme.setResultTime(dateFormat.format(calendar.getTime()));
        atsScheme.setResultExp(record.getResultExp());
        atsScheme.setResultEffect(record.getResultEffect());

        if(resultFile.isEmpty()){
            atsScheme.setResultFile(null);
        }else{
            String file = fileTools.saveFile("atsScheme",resultFile);

            atsScheme.setResultFile(file);
        }
        return atsSchemeMapperfx.updateByPrimaryKeySelective(atsScheme);
    }

    /**
     * 专家咨询：审核
     * @param expert
     * @param audit
     * @return
     */
    @Override
    public int insertAdvice(AtsSchemeExpert expert, AtsSchemeAudit audit,Integer schemeId) {

        AtsScheme atsScheme = atsSchemeMapperfx.findById(schemeId);
        //获取当前时间
        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        expert.setApplyForTime(dateFormat.format(calendar.getTime()));
        expert.setSaName(atsScheme.getSchemeName());

        expert.setIsva(0);
        expert.setAuditState("申请");
        atsScheme.setSort(10);
        atsSchemeMapperfx.updateByPrimaryKeySelective(atsScheme);
        if(atsScheme.getSchemeId()!=null){
            audit.setSaId(Integer.toString(schemeId));
            audit.setSaName(atsScheme.getSchemeName());
            audit.setCreatTime(new java.sql.Date(System.currentTimeMillis()));
            audit.setIsva(1);
            audit.setAuditState("申请");
            atsScheme.setSort(10);
            atsSchemeMapperfx.updateByPrimaryKeySelective(atsScheme);
            atsSchemeAuditMapperfx.insertSelective(audit);
        }
        return atsSchemeExpertMapperfx.insertSelective(expert);
    }

    @Override
    public int updateAdvice(AtsSchemeExpert expert, AtsSchemeAudit audit, Integer schemeId) {
        AtsScheme atsScheme = atsSchemeMapperfx.findById(schemeId);
        //获取当前时间
        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        expert.setApplyForTime(dateFormat.format(calendar.getTime()));
        expert.setIsva(0);
        expert.setAuditState("申请");
        atsScheme.setSort(10);
        atsSchemeMapperfx.updateByPrimaryKeySelective(atsScheme);
        if(atsScheme.getSchemeId()!=null){


            audit.setCreatTime(new java.sql.Date(System.currentTimeMillis()));
            audit.setIsva(1);
            audit.setAuditState("申请");
            atsScheme.setSort(10);
            atsSchemeMapperfx.updateByPrimaryKeySelective(atsScheme);
            atsSchemeAuditMapperfx.updateByPrimaryKeySelective(audit);
        }
        return atsSchemeExpertMapperfx.updateByPrimaryKeySelective(expert);
    }

    /**
     * 修改状态：逻辑删除
     * @param schemeId
     * @return
     */
    @Override
    public int updateId(int schemeId) {
        AtsScheme atsScheme = new AtsScheme();
        atsScheme.setSchemeId(schemeId);
        atsScheme.setIsva(0);
        return atsSchemeMapperfx.updateByPrimaryKeySelective(atsScheme);
    }

    @Override
    public AtsScheme selectByPrimaryKey(Integer schemeId) {
        return null;
    }

    /**
     * 修改显示
     * @param record
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(AtsScheme record) {
        AtsScheme atsScheme = atsSchemeMapperfx.findById(record.getSchemeId());
        record.setSchemeName(atsScheme.getSchemeName());
        record.setYear(atsScheme.getYear());
        record.setMonth(atsScheme.getMonth());
        record.setFile1(atsScheme.getFile1());
        record.setFile2(atsScheme.getFile2());
        record.setFile3(atsScheme.getFile3());

        return atsSchemeMapperfx.updateByPrimaryKeySelective(record);
    }

    /**
     * 修改
     * @param record
     * @return
     */
    @Override
    public int updateByPrimaryKey(AtsScheme record, MultipartFile file,MultipartFile file2,MultipartFile file3) {
       //时间
        /*String[] str = record.getMonth().split("-");
        record.setYear(str[0]);
        record.setMonth(str[1]);*/
        //清空复选框选中表数据
        atsSchemeAthleteMapperfx.deleteCheckbox(record.getSchemeId());
        if(record.getAthleteId()!=null &&!record.getAthleteId().equals("")){
            String[] strs = record.getAthleteId().split(",");
            for(int i=0;i<strs.length;i++){
                AtsSchemeAthlete atsSchemeAthlete = new AtsSchemeAthlete();
                atsSchemeAthlete.setSchemeId(record.getSchemeId());
                atsSchemeAthlete.setSchemeName(record.getSchemeName());
                atsSchemeAthlete.setAthleteId(Integer.valueOf(strs[i]));
                AtsEmpAthlete athlete = atsEmpAthleteMapper.selectByPrimaryKey(Integer.valueOf(strs[i]));
                System.out.println(athlete.getAthleteName()+"运动员姓名");
                atsSchemeAthlete.setAthleteName(athlete.getAthleteName());
                atsSchemeAthleteMapperfx.insertSelective(atsSchemeAthlete);
            }
        }

        try {
            if(file.isEmpty()){
                record.setFile1(null);
            }else{
                String fileOne = fileTools.saveFile("atsScheme",file);

                record.setFile1(fileOne);
            }

            if(file2.isEmpty()){
                record.setFile2(null);
            }else{
                String fileTwo = fileTools.saveFile("atsScheme",file2);

                record.setFile2(fileTwo);
            }

            if(file3.isEmpty()){
                record.setFile3(null);
            }else{
                String fileThree = fileTools.saveFile("atsScheme",file3);

                record.setFile3(fileThree);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return atsSchemeMapperfx.updateByPrimaryKeySelective(record);
    }

    /**
     * 删除
     * @param schemeId
     * @return
     */
    @Override
    public int deleteCheckbox(Integer schemeId) {
        return atsSchemeAthleteMapperfx.deleteCheckbox(schemeId);
    }

    /**
     *
     * @param schemeId
     * @param num
     * @param session
     * @return
     */

    @Override
    public int updateisRead(Integer schemeId, Integer num, HttpSession session) {
        int nums = 0 ;
        UserVo userVo = (UserVo) session.getAttribute("user");
        System.out.println("lhc3838383"+num);
        if(userVo.getCompanyId().equals("4")){

            List<AtsSchemeAthlete> list = atsSchemeAthleteMapperfx.selectisRead(Integer.valueOf(schemeId),Integer.valueOf(userVo.getClerkId()));
            AtsSchemeAthlete atsSchemeAthlete = new AtsSchemeAthlete();
            if(list.size()>0){
                atsSchemeAthlete  = list.get(0);
                String str = atsSchemeAthlete.getIsRead();
                    if(str.indexOf(String.valueOf(num))!=1){
                      atsSchemeAthlete.setIsRead(str+num+" ");
                    }else if(str.indexOf(String.valueOf(num))!=2){
                        atsSchemeAthlete.setIsRead(str+num+" ");
                }else if(str.indexOf(String.valueOf(num))!=3){
                        atsSchemeAthlete.setIsRead(str+num+" ");
                    }
            }
            nums = atsSchemeAthleteMapperfx.updateisRead(atsSchemeAthlete);
        }
         return nums ;
    }




    @Override
    public List<AtsEmpAthlete> findAllselects(HttpSession session) {
        UserVo userVo = (UserVo)session.getAttribute("user");
        if(userVo.getCompanyId().equals("2")){
            List<AtsEmpAthlete> coach = atsEmpAthleteMapper.selectByCoachId(Integer.valueOf(userVo.getClerkId()));
            return coach;
        }else{
            AtsEmpAthlete atsEmpAthlete=new AtsEmpAthlete();
            List<AtsEmpAthlete> list = atsEmpAthleteMapper.findAll(atsEmpAthlete);
            return list;
        }

    }





    @Override
    public List<AtsSchemeExpert> findExperts(Integer schemeId) {
        List<AtsSchemeExpert> expert = atsSchemeExpertMapperfx.findExperts(schemeId);

        return expert;
    }

    @Override
    public int huifuExpert(AtsSchemeExpert expert,AtsSchemeAudit audit,Integer schemeId) {
       AtsSchemeExpert experts = atsSchemeExpertMapperfx.findById(schemeId);
        System.out.println("expert.getSchemeId()"+schemeId);
       experts.setResults(expert.getResults());
       experts.setAuditState("专家已回复");
       experts.setSort(40);
       AtsSchemeAudit audits = atsSchemeAuditMapperfx.findById(Integer.toString(schemeId));
       audits.setAuditState("专家已回复");
       audits.setSort(40);
       atsSchemeAuditMapperfx.updateByPrimaryKeySelective(audits);
        return atsSchemeExpertMapperfx.updateByPrimaryKeySelective(experts);
    }

    @Override
    public AtsSchemeExpert findByIdChakanExpertQuanxian(Integer schemeId) {
        AtsSchemeExpert atsSchemeExpert = atsSchemeExpertMapperfx.findByIdChakanQuanxian(schemeId);
        return atsSchemeExpert;
    }

    @Override
    public AtsSchemeAthlete findByIdChakanAthleteQuanxian(Integer schemeId) {
        AtsSchemeAthlete atsSchemeAthlete = atsSchemeAthleteMapperfx.findByIdChakanQuanxian(schemeId);
        return atsSchemeAthlete;
    }

    @Override
    public XWPFDocument createWord(String userName, String schemeId, String contextPath) {
        XWPFHelper xh=null;
        //按方案id查询方案
        AtsScheme atsScheme=this.findById(Integer.valueOf(schemeId));
        //按方案id查询方案对应的运动员
        List<AtsSchemeAthlete> atsSchemeAthleteList=atsSchemeAthleteMapperfx.selectCheckbox(Integer.valueOf(schemeId));
        String athlete="";
        if(atsSchemeAthleteList.size()>0){
            for (int i = 0; i < atsSchemeAthleteList.size(); i++) {
                AtsSchemeAthlete schemeAthlete =  atsSchemeAthleteList.get(i);
                athlete+=schemeAthlete.getAthleteName()+"、";
            }
            athlete=athlete.substring(0,athlete.length()-1);
        }
        //按方案id查询审核表信息
        AtsSchemeAudit atsSchemeAudit=atsSchemeAuditMapperfx.findById(schemeId);


        if(atsSchemeAudit==null){
            atsSchemeAudit = new AtsSchemeAudit();
        }
        //按方案id查询专家咨询信息
        AtsSchemeExpert atsSchemeExpert=atsSchemeExpertMapperfx.findById(Integer.valueOf(schemeId));
        if(atsSchemeExpert!=null){
            if(atsSchemeExpert.getApplyForTime()!=null){

                atsSchemeExpert.setRemark(atsSchemeExpert.getApplyForTime());
            }
        }
        if(atsSchemeExpert==null){
            atsSchemeExpert = new AtsSchemeExpert();
        }

        ExportWordAddData exportWordAddData=new ExportWordAddData();

        XWPFDocument document=exportWordAddData.exportWord(userName,atsScheme,athlete,atsSchemeAudit,atsSchemeExpert,contextPath);

        return document;

    }


}
